package com.cyj.springbootservice.controller.dept;


import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.cyj.springbootservice.api.entity.SysDept;
import com.cyj.springbootservice.api.entity.SysDeptRelation;
import com.cyj.springbootservice.service.SysDeptRelationService;
import com.cyj.springbootservice.service.SysDeptService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @description:
 * @Author C_Y_J
 * @create 2022/5/10 10:19
 **/
@RestController
@AllArgsConstructor
@RequestMapping("/dept")
public class SysDeptController {

    private final SysDeptService sysDeptService;

    private final SysDeptRelationService relationService;

    /**
     * 获取部门树形结构
     *
     * @return
     */
    @GetMapping(value = "/tree")
    public R<List<Tree<Integer>>> getTree() {
        return R.ok(sysDeptService.selectTree());
    }

    /**
     * 添加
     *
     * @return
     */
    @PostMapping("/save")
    public R<Boolean> save() {
        SysDept sysDept = new SysDept();
        sysDept.setName("部门B");
        sysDept.setParentId(20);
        sysDept.setSort(3);
        return R.ok(sysDeptService.saveDept(sysDept));
    }

    /**
     * 编辑
     *
     * @param sysDept
     * @return
     */
    @PostMapping("/update")
    public R update(@Valid @RequestBody SysDept sysDept) {
        return R.ok(sysDeptService.updateDeptById(sysDept));
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R removeById(@PathVariable Integer id) {
        return R.ok(sysDeptService.removeDeptById(id));
    }

    /**
     * 查收子级列表
     *
     * @return 返回子级
     */
    @GetMapping(value = "/getDescendantList/{deptId}")
    public R getDescendantList(@PathVariable Integer deptId) {
        List<SysDeptRelation> list = relationService.list(Wrappers.<SysDeptRelation>lambdaQuery()
                .eq(SysDeptRelation::getAncestor, deptId));
        return R.ok(list);
    }

}

